#include "configfile.h"

#include <QFileInfo>
#include <QSettings>
#include <qDebug>

configfile::configfile() {}


QString configfile::configFileName="test20240829.ini";
QString configfile::Account="admin";
QString configfile::password="admin";
QString configfile::remoteIp="127.0.0.1";
int configfile::remotePort=502;

//首先检擦下存不存在文件，如果不存在就新建，存在就读写操作
bool configfile::isConfigFileExist()
{

    QFileInfo fileInfo(configfile::configFileName);
    if(fileInfo.isFile())
    {
        //存在情况下，看看内容全不全
        QFile file(configfile::configFileName);
        if (file.size() == 0) {
            configfile::newConfigFile();
            return false;
        }
        //如果配置文件不完整,则以初始值继续运行,并生成配置文件
        if (file.open(QFile::ReadOnly)) {
            bool ok = true;
            while (!file.atEnd()) {
                QString line = file.readLine();
                line = line.replace("\r", "");
                line = line.replace("\n", "");
                QStringList list = line.split("=");

                if (list.count() == 2) {
                    if (list.at(1) == "") {
                        ok = false;
                        break;
                    }
                }
            }

            if (!ok) {
                configfile::newConfigFile();
                return false;
            }
        } else {
            configfile::newConfigFile();
            return false;
        }
        return true;
    }else {
        configfile::newConfigFile();
        return false;
    }
}


//新建配置文件
void configfile::newConfigFile()
{
    writeConfigFile();
}

//读取配置文件
void configfile::readConfigFile()
{
    //先判断配置文件是否存在
    if (!isConfigFileExist()) {
        return;
    }

    QSettings set(configfile::configFileName, QSettings::IniFormat);//创建了一个QSettings对象，用于读取INI格式的配置文件
    set.setIniCodec("utf-8");//设置了INI文件的编码格式为UTF-8，确保能够正确读取包含非ASCII字符的配置项
    set.beginGroup("mysql");//开始读取名为"mysql"的组中的配置项。beginGroup函数用于指定当前操作的组
    configfile::Account = set.value("Account",configfile::Account).toString();
    configfile::password = set.value("password",configfile::password).toString();
    set.endGroup();

    qDebug()<<configfile::Account <<","<<configfile::password;

    set.beginGroup("net");
    configfile::Account = set.value("Account",configfile::Account).toString();
    configfile::password = set.value("password",configfile::password).toString();
    set.endGroup();
    qDebug()<<configfile::Account <<","<<configfile::password;
}

//写入配置文件
void configfile::writeConfigFile()
{
    //下面这段应该会自动生成配置文件？
    QSettings set(configfile::configFileName, QSettings::IniFormat);
    set.beginGroup("mysql");
    set.setValue("Account",configfile::Account);
    set.setValue("password",configfile::password);
    set.endGroup();

    set.beginGroup("net");
    set.setValue("remoteIp",configfile::remoteIp);
    set.setValue("remotePort",configfile::remotePort);
    set.endGroup();
}
